﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.Configuration;
using System.Data.SqlClient;
using Streambolics.Data;

namespace Ewma
{
    public class CommonWebPage : System.Web.UI.Page
    {
        private string _ConnectionString;
        private Configuration _WebConfig;
        private SqlConnection _Database;

        protected bool IsAppHarborSecureConnection ()
        {
            return string.Equals (Request.Headers["X-Forwarded-Proto"],
                   "https",
                   StringComparison.InvariantCultureIgnoreCase);
        }

        protected bool IsSecure ()
        {
            return Request.IsLocal
            || Request.IsSecureConnection
            || IsAppHarborSecureConnection ();
        }

        protected Configuration WebConfig
        {
            get
            {
                if (_WebConfig == null)
                {
                    _WebConfig = WebConfigurationManager.OpenWebConfiguration ("/");
                }
                return _WebConfig;
            }
        }

        protected string ConnectionString
        {
            get
            {
                if (_ConnectionString == null)
                {
                    _ConnectionString = WebConfig.ConnectionStrings.ConnectionStrings["ApplicationServices"].ConnectionString;
                }
                return _ConnectionString;
            }
        }

        protected SqlConnection Database
        {
            get
            {
                if (_Database == null)
                {
                    _Database = new SqlConnection (ConnectionString);
                    _Database.Open ();
                }
                return _Database;
            }
        }

        protected SqlDataReader ReadFromDatabase (string aSql)
        {
            return new SqlCommand (aSql, Database).ExecuteReader ();
        }

        protected override void OnUnload (EventArgs e)
        {
            base.OnUnload (e);
            if (_Database != null)
            {
                _Database.Close ();
                _Database.Dispose ();
                _Database = null;
            }
        }

        protected bool TableExists (string aTableName)
        {
            return false;
        }

        protected void AccessTable<T> (string aTableName) where T : DataTable, new()
        {
            if (!TableExists (aTableName))
            {
                T x = new T ();
                x.MakeStructure (aTableName, Database);
            }
        }
    }
}